$(document).ready(function () {
    // 从localStorage加载留言
    function loadMessages() {
        let messages;
        try {
            messages = JSON.parse(localStorage.getItem('messages') || '[]');
            // 为现有留言添加头像属性（如果不存在）
            messages.forEach(message => {
                if (!message.avatar) {
                    message.avatar = Math.floor(Math.random() * 3) + 1;
                }
                // 确保留言对象有comments数组
                if (!message.comments) {
                    message.comments = [];
                }
                // 初始化留言点赞数
                if (message.likes === undefined) {
                    message.likes = 0;
                }
                // 初始化评论点赞数
                message.comments.forEach(comment => {
                    if (comment.likes === undefined) {
                        comment.likes = 0;
                    }
                });
            });
            localStorage.setItem('messages', JSON.stringify(messages));
        } catch (e) {
            console.error('Error parsing messages:', e);
            messages = [];
            localStorage.setItem('messages', JSON.stringify(messages));
        }
        const container = $('#messagesContainer');
        if (!container.length) {
            console.error('留言容器 #messagesContainer 未找到');
            return;
        }
        // 调试日志 - 显示加载的留言数量
        console.log('加载留言数量:', messages.length);
        container.empty();

        messages.forEach(message => {
            const messageElement = `
                <div class="message-item">
                    <div class="message-header">
                        <span class="message-nickname">${message.nickname}</span>
                        <span class="message-time">${message.time}</span>
                    </div>
                    <div class="message-content">${message.content}</div>
                    <div class="message-email">${message.email}</div>
                </div>
            `;
            // 使用jQuery创建元素而非字符串拼接，避免潜在的HTML解析问题
            const messageDiv = $('<div>').addClass('message-item').prepend(`<img src="headimgs/head${message.avatar}.png" class="message-avatar">`);
            const headerDiv = $('<div>').addClass('message-header');
            headerDiv.append($('<span>').addClass('message-nickname').text(message.nickname));
            headerDiv.append($('<span>').addClass('message-time').text(message.time));
            messageDiv.append(headerDiv);
            messageDiv.append($('<div>').addClass('message-content').text(message.content));
            // 点赞按钮和数量
            const likeDiv = $('<div>').addClass('like-container');
            const likeBtn = $('<button>').addClass('like-btn').html('<i class="like-icon">&#9825;</i>');
            const likeCount = $('<span>').addClass('like-count').text(message.likes);
            likeDiv.append(likeBtn).append(likeCount);
            messageDiv.append(likeDiv);

            // 初始化点赞状态
            if (message.likes > 0) {
                likeBtn.addClass('liked');
            }

            // 点赞事件
            likeBtn.click(function () {
                const isLiked = $(this).hasClass('liked');
                if (isLiked) {
                    message.likes--;
                    $(this).removeClass('liked');
                } else {
                    message.likes++;
                    $(this).addClass('liked');
                }
                likeCount.text(message.likes);
                // 更新localStorage
                let messages = JSON.parse(localStorage.getItem('messages') || '[]');
                const messageIndex = messages.findIndex(m => m.timestamp === message.timestamp);
                if (messageIndex !== -1) {
                    messages[messageIndex].likes = message.likes;
                    localStorage.setItem('messages', JSON.stringify(messages));
                }
            });
            // 移除邮箱显示
            // 添加回复按钮
            const replyBtn = $('<button>').addClass('reply-btn').text('回复');
            messageDiv.append(replyBtn);

            // 评论容器
            const commentsContainer = $('<div>').addClass('comments-container');
            messageDiv.append(commentsContainer);

            // 评论表单 (默认隐藏)
            const commentForm = $('<div>').addClass('comment-form').css('display', 'none');
            commentForm.html(`
                    <div class="form-group">
                        <label for="comment-nickname-${message.timestamp}">昵称:</label>
                        <input type="text" class="form-control comment-nickname" placeholder="请输入您的昵称" required>
                        <div class="invalid-feedback">请输入昵称</div>
                    </div>
                    <div class="form-group">
                        <label for="comment-email-${message.timestamp}">邮箱:</label>
                        <input type="email" class="form-control comment-email" placeholder="请输入您的邮箱" required pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$">
                        <div class="invalid-feedback">请输入有效的邮箱地址</div>
                    </div>
                    <div class="form-group">
                        <label for="comment-content-${message.timestamp}">评论内容:</label>
                        <textarea class="form-control comment-content" rows="4" placeholder="请输入评论内容" required></textarea>
                        <div class="invalid-feedback">请输入评论内容</div>
                    </div>
                    <button type="button" class="btn btn-primary submit-comment">提交评论</button>
                `);

            // 添加实时验证
            const validateField = (field, regex, errorMessage) => {
                const value = field.val().trim();
                const isValid = regex ? regex.test(value) : value !== '';
                if (!isValid) {
                    field.addClass('is-invalid');
                    field.next('.invalid-feedback').text(errorMessage);
                } else {
                    field.removeClass('is-invalid');
                }
                return isValid;
            };

            // 昵称验证
            commentForm.find('.comment-nickname').on('input', function () {
                validateField($(this), null, '请输入昵称');
            });

            // 邮箱验证
            commentForm.find('.comment-email').on('input', function () {
                const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
                validateField($(this), emailRegex, '请输入有效的邮箱地址');
            });

            // 评论内容验证
            commentForm.find('.comment-content').on('input', function () {
                validateField($(this), null, '请输入评论内容');
            });
            messageDiv.append(commentForm);

            // 渲染现有评论
            message.comments.forEach(comment => {
                const commentElement = $('<div>').addClass('comment-item');
                commentElement.html(`
                    <div style="display: flex; align-items: flex-start;">
                        <img src="headimgs/head${comment.avatar}.png" class="message-avatar" style="margin-right: 10px;">
                        <div style="flex: 1; margin-left: 10px; display: flex; flex-direction: column;">
                            <div class="comment-header">
                                <span class="comment-nickname">${comment.nickname}</span>
                                <span class="comment-time">${new Date(comment.timestamp).toLocaleString()}</span>
                            </div>
                            <div class="comment-content" style="margin-top: 8px;">${comment.content}</div>
                        <div class="like-container">
                            <button class="like-btn"><i class="like-icon">&#9825;</i></button>
                            <span class="like-count">${comment.likes}</span>
                        </div>
                        </div>
                    </div>
                `);
                commentsContainer.append(commentElement);

                // 评论点赞功能
                const commentLikeBtn = commentElement.find('.like-btn');
                const commentLikeCount = commentElement.find('.like-count');

                // 初始化评论点赞状态
                if (comment.likes > 0) {
                    commentLikeBtn.addClass('liked');
                }

                // 评论点赞事件
                commentLikeBtn.click(function () {
                    const isLiked = $(this).hasClass('liked');
                    if (isLiked) {
                        comment.likes--;
                        $(this).removeClass('liked');
                    } else {
                        comment.likes++;
                        $(this).addClass('liked');
                    }
                    commentLikeCount.text(comment.likes);

                    // 更新localStorage中的评论点赞数
                    let messages = JSON.parse(localStorage.getItem('messages') || '[]');
                    const messageIndex = messages.findIndex(m => m.timestamp === message.timestamp);
                    if (messageIndex !== -1) {
                        const commentIndex = messages[messageIndex].comments.findIndex(c => c.timestamp === comment.timestamp);
                        if (commentIndex !== -1) {
                            messages[messageIndex].comments[commentIndex].likes = comment.likes;
                            localStorage.setItem('messages', JSON.stringify(messages));
                        }
                    }
                });
            });

            // 回复按钮点击事件
            replyBtn.click(function () {
                commentForm.toggle();
            });

            // 评论提交事件
            commentForm.find('.submit-comment').click(function () {
                const commentNickname = commentForm.find('.comment-nickname').val().trim();
                const commentEmail = commentForm.find('.comment-email').val().trim();
                const commentContent = commentForm.find('.comment-content').val().trim();
                const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

                // 表单验证
                if (!commentNickname) {
                    alert('请输入昵称');
                    return;
                }
                if (!commentEmail || !emailRegex.test(commentEmail)) {
                    alert('请输入有效的邮箱地址');
                    return;
                }
                if (!commentContent) {
                    alert('请输入评论内容');
                    return;
                }

                if (commentNickname && commentEmail && commentContent) {
                    const newComment = {
                        nickname: commentNickname,
                        email: commentEmail,
                        content: commentContent,
                        timestamp: new Date().toISOString(),
                        avatar: Math.floor(Math.random() * 3) + 1,
                        likes: 0
                    };

                    // 保存评论到对应留言
                    let messages = JSON.parse(localStorage.getItem('messages') || '[]');
                    const messageIndex = messages.findIndex(m => m.timestamp === message.timestamp);
                    if (messageIndex !== -1) {
                        messages[messageIndex].comments.push(newComment);
                        localStorage.setItem('messages', JSON.stringify(messages));
                        loadMessages(); // 重新加载留言列表
                    }
                }
            });
            container.append(messageDiv);
        });
    }

    // 保存留言到localStorage
    function saveMessage(message) {
        console.log('开始保存留言:', message);
        let messages;
        try {
            messages = JSON.parse(localStorage.getItem('messages') || '[]');
            console.log('从localStorage加载的留言数量:', messages.length);
        } catch (e) {
            console.error('Error parsing messages:', e);
            messages = [];
        }
        messages.push(message);
        localStorage.setItem('messages', JSON.stringify(messages));
        console.log('留言保存成功，当前留言总数:', messages.length);
    }

    // 处理表单提交
    $('#messageForm').submit(function (e) {
        e.preventDefault();
        console.log('留言表单提交事件触发');

        // 获取表单数据
        const nickname = $('#nickname').val().trim();
        const email = $('#email').val().trim();
        const content = $('#content').val().trim();
        console.log('表单数据:', { nickname, email, content });

        if (!nickname || !email || !content) {
            console.log('表单数据不完整');
            return;
        }

        // 创建新留言对象
        const newMessage = {
            nickname: nickname,
            email: email,
            content: content,
            timestamp: new Date().toISOString(),
            avatar: Math.floor(Math.random() * 3) + 1,
            comments: [],
            likes: 0
        };

        // 调试日志 - 显示提交的留言数据
        console.log('提交新留言:', newMessage);
        // 保存留言并重新加载显示
        saveMessage(newMessage);
        loadMessages();

        // 重置表单
        this.reset();
    });

    // 确保DOM完全加载后执行初始加载，并添加微小延迟避免与其他组件加载冲突
    $(document).ready(function () {
        setTimeout(loadMessages, 100);
    });
});